<template>
  <div class="masker" v-if="isShow"></div>
  <div class="payBox" v-if="isShow && (payType == 'batch' || payType == 'all')">
    <header>
      <div class="close2" @click="changeIsShow"></div>
      <h2 class="title" v-if="payType == 'batch'">批量購買集數</h2>
      <h2 class="title" v-if="payType == 'all'">購買整部</h2>
    </header>
    <div class="form">
      <div class="form-item">
        <label for="episodeCount" v-if="payType == 'batch'">
          <span>購買劇集：</span>
          <g v-if="!isExpire">
            <g v-if="count == 1">第{{ payCount + freeCount + count }}集</g>
            <g v-else>第{{ payCount + freeCount + 1 }}-{{ payEp ? payEp : payCount + freeCount + count }}集</g>
          </g>
          <g v-if="isExpire">
            <g v-if="count == 1">第{{ expireInitEp }}集</g>
            <g v-else>第{{ expireInitEp }}-{{ payEp ? payEp : expireInitEp + count - 1 }}集</g>
          </g>

        </label>
        <label for="episodeCount" v-if="payType == 'all'">
          <span>購買劇集：</span>
          <g v-if="!isExpire">
            <g v-if="count == 1">第{{ payCount + freeCount + count }}集</g>
            <g v-else>第{{ payCount + freeCount + 1 }}-{{ payEp ? payEp : totalEpisodes }}集</g>
          </g>
          <g v-if="isExpire">
            <g v-if="count == 1">第{{ payCount + freeCount + count }}集</g>
            <g v-else>第{{ expireInitEp }}-{{ payEp ? payEp : totalEpisodes }}集</g>
          </g>
        </label>
        <div class="number">
          <span>購買集數：</span>
          <input v-if="!payEp && payType != 'all'" type="number" id="episodeCount" v-model="count" min="1"
            @input="onInput" />
          <label style="margin-left: 0;" v-if="payEp || payType == 'all'">{{ count }}</label>
        </div>
      </div>

      <div class="price">
        <b v-if="discountRate < 1">原價：</b>
        <b v-else>應付金額：</b>
        <span :class="{ strike: discountRate != 1 }">${{ totalPrice }}</span>
      </div>
      <div class="price" v-if="discountRate < 1">
        <b>折扣價({{ discountRate * 10 }} 折)：</b>
        <span>${{ totalPriceNew }}</span>
      </div>
      <button @click="handleBuy">確定購買</button>
    </div>
    <div class="discount-rules" v-if="rebate.length > 0">
      <p>優惠規則：</p>
      <ul>
        <li v-for="item in rebate">購買集數 >= {{ item.num }} ：享 {{ item.rebate * 10 }} 折</li>
      </ul>
      <!-- <p>目前折扣：
            <strong v-if="discountRate < 1">{{ (discountRate * 10) }} 折</strong>
            <strong v-else>无折扣</strong>
          </p> -->
    </div>
    <div class="bg_img" v-if="rebate.length > 0">
      <img width="70" src="https://yyfuns.com/static/logoZ.png" alt="">
    </div>
  </div>
  <!-- <div class="payBox" v-if="isShow && payType == 'all'">
        <div class="close2" @click="changeIsShow"></div>
        <h2 class="title">購買本集(第{{nowEpisodes}}集)</h2>
        <div class="form">
            <div class="price">應付金額：<span>${{ totalPrice }}</span></div>
            <button @click="handleBuy">確定購買</button>
        </div>
    </div> -->

  <div class="payBox" v-if="isShow && payType == 'payOne'" style="padding-top: 7px;">
    <div class="close2" @click="changeIsShow"></div>
    <h2 class="title" style="padding-left: 10px;">購買本集(第{{ payEp }}集)</h2>
    <div class="form" style="margin-top: 20px;">
      <div class="price" style="margin-left:120px;">應付金額：<span>${{ totalPrice }}</span></div>
      <button @click="handleBuy">確定購買</button>
    </div>
  </div>

  <div class="payBox" v-if="isShow && payType == 'pack'" style="padding-top: 7px;">
    <div class="close2" @click="changeIsShow"></div>
    <h2 class="title" style="padding-left: 10px;">購買劇集</h2>
    <div class="form" style="margin-top: 20px;">
      <div class="choose">
        <p>選擇購買集數：</p>
        <el-select @change="handleChange" v-model="packPrice" placeholder="Select" size="default" style="width: 80px">
            <el-option v-for="item in rebate" :key="item.num" :label="item.num" :value="item.rebate"/>
        </el-select>
      </div>
      <div class="price" style="margin-left:120px;">應付金額：<span>${{ packPrice }}</span></div>
      <button @click="handleBuy">確定購買</button>
      <span>小貼士：您購買的集數可用來觀看本平台所有劇集</span>
    </div>
  </div>

  <div ref="recharge_content" class="recharge_content" v-if="isEconomical">
    <RechargeComp :cText="cText" :isEconomical="isEconomical" :closeBox="closeBox" :price="free_type == 2 ? totalPriceNew : packPrice" :free_type="free_type"
      :videoSku='sku' :openDialog="openDialog" :isSandPay="true" :setPayResult="setPayResult" :count="count" />
  </div>
  <div class="blocker" v-if="isEconomical"></div>

  <div v-if="lang == 'en'">
    <Dialog :title="'Please confirm payment'" :title2="'Once the payment is successful, you can watch the video'"
      :cancel_title="'Not yet paid'" :sub_title="'Payment completed'" :visible="dialog_show" :handleClose='dialog_hide'
      :paySubmit="paySubmit" />
  </div>
  <div v-if="lang == 'zh'">
    <Dialog :title="'請確認付款'" :title2="'支付成功即可觀看視頻'" :cancel_title="'還未支付'" :sub_title="'已完成支付'" :visible="dialog_show"
      :handleClose='dialog_hide' :paySubmit="paySubmit" />
  </div>

  <!-- <div class="pay_result" v-show="showPayResultStore.isPayResult">
        <div class="close" @click="close_pay_result"></div>
        <iframe :src="pay_result_src" width="100%" height="100%" frameborder="0" ></iframe>
    </div> -->
</template>

<script setup>
import RechargeComp from "@/components/recharge/rechargeComp/index.vue"
import Dialog from "@/components/Dialog/index.vue"
import { useShowPayResult } from "@/store/modules/isShowPayResult"
const route = useRoute();
const props = defineProps(['isShow', 'changeIsShow', 'payType', 'episode_money', 'nowEpisodes', 'rebate', 'payEp', 'payCount', 'free_episode', 'totalEpisodes', 'getTheateList', 'isExpire', 'freeCount', 'episode_info', 'expireInitEp','free_type','getUserInfo'])
let { isShow,changeIsShow, episode_money, rebate, payEp, payType, payCount, free_episode, totalEpisodes, getTheateList, isExpire, freeCount, episode_info, expireInitEp,free_type,getUserInfo } = toRefs(props)
const count = ref(1)
const cText = ref([])
console.log(rebate)
const packPrice = ref(0)

// 监听 rebate 变化（如果 rebate 可能异步加载）
watch(rebate, (newVal) => {
  console.log('rebate 变化：', newVal);
  
  if(newVal?.length > 0) {
    packPrice.value = newVal[0].rebate
  }
}, { immediate: true })

const maxCount = computed(() => {
  if (isExpire.value) {
    return totalEpisodes.value - expireInitEp.value + 1
  } else {
    return totalEpisodes.value - (payCount.value + freeCount.value)
  }

})
const onInput = (e) => {
  const value = e.target.value
  console.log(e);


  if (value === '') {
    count.value = ''
    return
  }

  const num = Number(value)
  if (isNaN(num)) return

  const max = maxCount.value
  if (num > max) {
    count.value = max
    ElMessage.warning(`最多可購買 ${max} 集`)
  } else if (num < 1) {
    count.value = 1
  } else {
    count.value = num
  }
}
const handleBuy = () => {
  if (count.value < 1) {
    ElMessage.error('請輸入有效的購買集數')
    return
  }
  // 你可以在这里添加实际的购买逻辑
  console.log(`购买 ${count.value} 集`)
  // 然后关闭弹窗
  changeIsShow.value()
  console.log(isExpire.value, 'isExpire.value');

  if (!isExpire.value) {
    if (payEp.value) {
      cText.value = [payCount.value + freeCount.value + 1, payEp.value]
    } else if (payType.value == 'batch') {
      cText.value = [payCount.value + freeCount.value + 1, payCount.value + freeCount.value + count.value]
    } else if (payType.value == 'all') {
      cText.value = [payCount.value + freeCount.value + 1, totalEpisodes.value]
    }
  } else {
    const lastPaidItem = episode_info.value.slice().reverse().find(item => item.is_pay === 1)
    let initEp = 0
    if (lastPaidItem) {
      initEp = lastPaidItem.index
    }
    if (payEp.value) {
      cText.value = [initEp + 1, payEp.value]
    } else if (payType.value == 'batch') {
      cText.value = [initEp + 1, initEp + count.value]
    } else if (payType.value == 'all') {
      cText.value = [initEp + 1, totalEpisodes.value]
    }

    if (payEp.value && payEp.value < initEp) {
      cText.value = [1, episode_info.value[payEp.value - 1].index]
    }
  }

  cText.value = cText.value.join(',')
  console.log(cText.value);
  if(free_type.value == 1){
    const o = rebate.value.find(item=>item.rebate == packPrice.value)
    count.value = o.num
  }

  isEconomical.value = true
  const postData = {
    type: 'AddToCart',
    price: free_type.value == 2 ? totalPriceNew.value : packPrice.value
  }
  window.parent.postMessage(postData, '*');

}
const lang = ref('')
if (localStorage.getItem('lang') == 'en') {
  lang.value = 'en'
} else {
  lang.value = 'zh'
}


const recharge_content = ref()
let isEconomical = ref(false)
const closeBox = () => {
  isEconomical.value = false
  recharge_content.value.style.top = '100%'
};

const sku = route.query.id

const totalPriceNew = computed(() => {
  if (count.value <= 0) return '0.00'
  const raw = count.value * episode_money.value
  const discounted = raw * discountRate.value
  return discounted.toFixed(2)
})

const totalPrice = computed(() => {
  return count.value > 0 ? (count.value * episode_money.value).toFixed(2) : '0.00'
})


let dialog_show = ref(false)
const dialog_hide = () => {
  dialog_show.value = false
}
const openDialog = () => {
  dialog_show.value = true
}


const paySubmit = () => {
  dialog_hide()
  // getTheateList.value()
  getUserInfo.value()
}

// const pay_result_src = ref('')
// const showPayResultStore = useShowPayResult()
const setPayResult = (url) => {
  // showPayResultStore.showPayResult()
  // pay_result_src.value = url
  // console.log(pay_result_src.value,'pay_result_src.value');
  const data = {
    name: 'setPayResult',
    url
  }
  window.parent.postMessage(data, '*');
  isEconomical.value = false
}
// const close_pay_result = () => {
//   showPayResultStore.unPayResult()
//   pay_result_src.value = ''
// }

defineExpose({
  count
})

const discountRate = computed(() => {
  let currentRate = 1 // 每次重新开始计算
  for (const rule of rebate.value) {
    if (count.value >= Number(rule.num)) {
      currentRate = Math.min(currentRate, Number(rule.rebate))
    }
  }
  return currentRate
})


</script>

<style lang="less" scoped>
@main: #ff9e3d;
@hover: #e0861d;
@white-glass: rgba(255, 255, 255, 0.65);
@border: rgba(255, 255, 255, 0.3);
@text: #333;
@shadow: 0 16px 32px rgba(0, 0, 0, 0.15);

.payBox {
  width: 380px;
  padding: 15px 24px;
  padding-top: 35px;
  border-radius: 15px;
  // background: linear-gradient(1deg, #ffeeb8b0, #e6c982e0);
  backdrop-filter: blur(16px);
  background-image: url("");
  background-size: cover;
  background-position: right;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1001;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: popIn 0.3s ease-out;

  header {
    // background:linear-gradient(to bottom, #a56e40, #fffaf3);
    width: 100%;
    position: absolute;
    top: 0;
    border-radius: 15px 15px 0 0;
    padding: 8px 0 20px;
  }

  .discount-rules {
    margin-top: 30px;
    font-size: 15px;
    color: #434343;
    margin-left: 0px;
  }

  .discount-rules ul {
    margin: 5px 0;
    list-style-type: disc;
  }

  .discount-rules strong {
    color: #e91e63;
  }

  p {
    font-size: 16px;
  }

  .bg_img {
    position: absolute;
    right: 17px;
    bottom: 15px;
    // filter: invert(1) brightness(30);
  }
}

@keyframes popIn {
  0% {
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
  }

  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
}

.title {
  font-size: 22px;
  font-weight: 600;
  color: @text;
  text-align: left;
  padding-left: 23px;
  color: #745d4b;
  margin-top: 3px;
}

.form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
  margin-top: 30px;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(16px);
  box-shadow: 0 10px 30px #b5b5b540;
  border-radius: 12px;
  padding: 15px 0;
  span{
    color: #9d7c57;
    font-size: 13px;
  }
  .choose{
    display: flex;
    align-items: center;
    :deep(.el-select__wrapper) {
      height: 36px;
      border-radius: 4px !important;
    }
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-left: 20px;
    color: black;
  }

  label {
    font-size: 15px;
    color: #ff9e3d;

    // margin-left: 100px;
    span {
      color: black;
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: center;

    span {
      margin-left: 21px;
      margin-right: 0;
    }
  }

  input {
    margin: 0;
    width: 40px;
    padding: 1px 11px;
    border-radius: 32px;
    border: 1px solid #ddd;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.9);
    transition: all 0.3s ease;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
    color: black;

    &:focus {
      border-color: @main;
      box-shadow: 0 0 0 3px rgba(255, 158, 61, 0.2);
      outline: none;
    }
  }

  .price {
    font-size: 17px;
    color: black;
    margin-left: 20px;

    span {
      color: @main;
      font-size: 19px;
    }

    .strike {
      position: relative;
      display: inline-block;
      color: #999;
    }

    .strike::after {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      top: 50%;
      height: 2px;
      /* 控制粗细 */
      background-color: currentColor;
      transform: translateY(-50%);
      pointer-events: none;
      color: #df7b09;
    }
  }

  button {
    width: 90%;
    padding: 8px;
    font-size: 16px;
    font-weight: bold;
    color: #df7b09;
    background: linear-gradient(119deg, #fdbc6a, #fce7b4);
    border: none;
    border-radius: 45px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 4px 14px rgba(255, 158, 61, 0.3);
    margin-top: 5px;

    &:hover {
      filter: brightness(1.05);
      transform: translateY(-1px);
    }

    &:active {
      transform: scale(0.97);
    }
  }
}



.masker {
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  inset: 0;
  z-index: 1000;
}

.recharge_content {
  background-color: white;
  position: fixed;
  top: 50% !important;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  z-index: 10001;
  border-radius: 15px;
  padding: 20px 20px 50px;
  height: 680px;
  bottom: 0px;
  overflow: hidden;
  animation: popIn 0.3s ease-out;
}

.blocker {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  z-index: 9999 !important;
}

.pay_result {
  background-color: #fff;
  width: 600px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10000;
  height: 700px;
  border-radius: 15px;

  iframe {
    border-radius: 15px;
    position: relative;
    z-index: 2003;
  }

  .close {
    z-index: 9999;
  }

  .close:hover {
    cursor: pointer;
    background-image: url();
  }
}
</style>
